#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>

// 加载字体并返回一个TTF_Font指针
TTF_Font* loadFont(const char* fontFile, int fontSize) {
    TTF_Font* font = TTF_OpenFont(fontFile, fontSize);
    if (!font) {
        // 处理加载错误
        printf("Unable to load font %s! SDL_ttf Error: %s\n", fontFile, TTF_GetError());
    }
    return font;
}

// 创建包含文本的纹理
SDL_Texture* createTextTexture(SDL_Renderer* renderer, const char* text, TTF_Font* font, SDL_Color textColor) {

    SDL_Surface* textSurface = TTF_RenderText_Solid(font, text, textColor);
    if (!textSurface) {
        // 处理渲染错误
        printf("Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError());
        return NULL;
    }

    SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
    SDL_FreeSurface(textSurface);
    return textTexture;
}

int main() {
    // 初始化SDL、SDL_ttf
    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();

    // 创建窗口和渲染器
    SDL_Window* window = SDL_CreateWindow("SDL2 Text Display", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 800, 600, SDL_WINDOW_SHOWN);
    SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);

    // 加载字体
    TTF_Font* font = loadFont("./font/Songti.ttc", 128);
    if (!font) {
        // 处理加载字体错误
        return 1;
    }

    // 设置文本颜色
    SDL_Color textColor = {255, 255, 255, 255}; // 白色

    // 创建包含文本的纹理
    const char* text = "Hello, SDL2!";
    SDL_Texture* textTexture = createTextTexture(renderer, text, font, textColor);
    if (!textTexture) {
        // 处理创建文本纹理错误
        return 1;
    }

    // 主循环
    int quit = 0;
    SDL_Event e;
    while (!quit) {
        while (SDL_PollEvent(&e) != 0) {
            if (e.type == SDL_QUIT) {
                quit = 1;
            }
        }

        // 清空屏幕
        SDL_RenderClear(renderer);

        // 显示文本
        SDL_Rect destination = {100, 100, 120, 30}; // 文本在窗口中的位置和大小
        SDL_RenderCopy(renderer, textTexture, NULL, &destination);

        // 刷新屏幕
        SDL_RenderPresent(renderer);
    }

    // 释放资源
    TTF_CloseFont(font);
    SDL_DestroyTexture(textTexture);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    // 关闭SDL和SDL_ttf
    TTF_Quit();
    SDL_Quit();

    return 0;
}
